<template>
  <div class="chatList">
    <NewCard title="沟通">
      <!-- tab标签 -->
      <!-- <template slot="title" class="cut-menu">
        <el-radio-group v-model="showSearch">
          <el-radio-button :label="1">朋友</el-radio-button>
          <el-radio-button :label="2">进行中</el-radio-button>
          <el-radio-button :label="3">已完成</el-radio-button>
        </el-radio-group>
      </template>
      <!-- tab标签 end -->
      <div class="tab-list">
        <!-- 私聊 -->
        <div class="collapse-item" v-if="showSearch == 1">
          <div class="search-list" style="display: flex; justify-content: center; align-items: center;">
            <!-- 搜索框 -->
            <el-input v-model="keyword" placeholder="搜索" prefix-icon="el-icon-search"></el-input>
            <div class="addIcon">
              <img src="@/assets/images/tj_icon.png" @click="menuShow = true" />
              <div class="menubox" v-if="menuShow">
                <div class="mask_bg" @click="menuShow = false"></div>
                <div class="list">
                  <div class="item" @click="openAddOne()"><span>发起聊天</span></div>
                  <div class="item" @click="openAddGroup()"><span>发起群聊</span></div>
                </div>
              </div>
            </div>
          </div>
          <div class="list-box" ref="box">
            <ul>
              <!-- 目标任务沟通群 -->
              <li @click="showSearch = 2">
                <el-badge :value="taskUnreadNum" :max="99" :hidden="taskUnreadNum == 0 ? true : false" class="item">
                  <div class="avatarImg2">
                    <img src="@/assets/images/mubiao.svg" alt="">
                  </div>
                </el-badge>
                <div class="list-con">
                  <p class="concat-title">
                    <span>目标任务沟通群</span>
                    <span class="title-time"></span>
                  </p>
                  <p class="message">
                    <span>仅显示进行中的任务沟通群</span>
                  </p>
                </div>
              </li>
              <!-- 目标任务沟通群 end -->
              <!-- 应用服务群 -->
              <li @click="showSearch = 3">
                <el-badge :value="orderUnreadNum" :max="99" :hidden="orderUnreadNum == 0 ? true : false" class="item">
                  <div class="avatarImg2">
                    <img src="@/assets/images/fuwu.svg" alt="">
                  </div>
                </el-badge>
                <div class="list-con">
                  <p class="concat-title">
                    <span>应用服务沟通群</span>
                    <span class="title-time"></span>
                  </p>
                  <p class="message">
                    <span>问三师应用服务沟通群</span>
                  </p>
                </div>
              </li>
              <!-- 应用服务群 end -->

              <li v-for="(havingItem, havingIndex) in imList" :key="havingIndex" :id="havingIndex" v-trigger
                ref="havingUp" @click="chatIm(havingItem,havingIndex,1)"
                :class="{ active: currentIndex == havingItem.id }">
                <!-- 头像 -->
                <!--  :value="JSON.stringify(concatItem.unread)" -->
                <el-badge :value="havingItem.unreadNumber" :max="99" class="item"
                  :hidden="havingItem.unreadNumber == 0 ? true : false">
                  <div :class="['avatarImg2', 'groupAvatar', getMembersNum(havingItem.avatarArr) < 5 ?'big':'']" v-if="havingItem.type == 0">
                    <img v-for="(avatarImg,i) in getGroupAvatar(havingItem)" :key="i" :src="(avatarImg.avatar || DeAvatar) + '?x-oss-process=image/resize,m_fill,w_60,quality,q_60'"/>
                  </div>
                  <div class="avatarImg2" v-else>
                    <img :src="havingItem.icon||DeAvatar" alt="">
                  </div>
                </el-badge>
                <!-- 名称 -->
                <div class="list-con">
                  <p class="concat-title">
                    <span>{{ havingItem.name }}</span>
                    <!-- <span class="title-time"> {{ concatItem.createTime }}</span> -->
                    <span class="title-time">
                      {{ getTime2(havingItem) }}</span>
                  </p>
                  <p class="message">
                    <!-- <i class="el-icon-circle-check"></i> -->
                    <span>{{ getImMsg(havingItem) }}</span>
                    <!-- <span class="message_pic">
  <svg-icon
    icon-class="ywc_icon"
    v-if="havingItem.cancelTime"
  />
  <svg-icon icon-class="jxz_icon" v-else />
</span> -->
                  </p>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <!-- 私聊end -->
        <!-- 任务目标 -->
        <div class="collapse-item" v-if="showSearch == 2">
          <div class="search-list">
            <!-- 搜索框 -->
            <el-input v-model="keyword" placeholder="搜索" prefix-icon="el-icon-search"></el-input>
          </div>
          <div class="back" @click="showSearch = 1">
            <i class="el-icon-arrow-left"></i>返回
          </div>
          <div class="list-box" ref="box">
            <ul>
              <li v-for="(havingItem, havingIndex) in taskList" :key="havingIndex" :id="havingIndex" v-trigger
                ref="havingUp" @click="chatIm(havingItem,havingIndex)"
                :class="{ active: currentIndex == havingItem.id }">
                <!-- 头像 -->
                <!--  :value="JSON.stringify(concatItem.unread)" -->
                <el-badge :value="havingItem.unreadNumber" :max="99" class="item"
                  :hidden="havingItem.unreadNumber == 0 ? true : false">
                  <div :class="['avatarImg2', 'groupAvatar', getMembersNum(havingItem.avatarArr) < 5 ?'big':'']">
                    <img v-for="(avatarImg,i) in getGroupAvatar(havingItem)" :key="i" :src="(avatarImg.avatar || DeAvatar) + '?x-oss-process=image/resize,m_fill,w_60,quality,q_60'"/>
                  </div>
                </el-badge>
                <!-- 名称 -->
                <div class="list-con">
                  <p class="concat-title">
                    <span>{{ havingItem.name }}</span>
                    <!-- <span class="title-time"> {{ concatItem.createTime }}</span> -->
                    <span class="title-time">
                      {{ getTime2(havingItem) }}</span>
                  </p>
                  <p class="message">
                    <!-- <i class="el-icon-circle-check"></i> -->
                    <span>{{ getImMsg(havingItem) }}</span>
                  </p>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <!-- 任务目标 end -->
        <!-- 订单服务 -->
        <div class="collapse-item" v-if="showSearch == 3">
          <div class="search-list">
            <!-- 搜索框 -->
            <el-input v-model="keyword" placeholder="搜索" prefix-icon="el-icon-search"></el-input>
          </div>
          <div class="back" @click="showSearch = 1">
            <i class="el-icon-arrow-left"></i>返回
          </div>
          <div class="list-box" ref="box">
            <ul class="successCome">
              <li v-for="(successItem, successIndex) in filConList" :key="successIndex" :id="successIndex"
                ref="successDefault" class="successDefault" @click="
chatSay2(
successItem,
successIndex,
)
" :class="{ active: currentIndex == successItem.id }">
                <el-badge :value="successItem.unread" :max="99" class="item"
                  :hidden="successItem.unread == 0 ? true : false">
                  <div :class="['avatarImg2', 'groupAvatar', getMembersNum(successItem.avatarArr) < 5 ?'big':'']">
                    <img v-for="(avatarImg,i) in getGroupAvatar(successItem)" :key="i" :src="(avatarImg.avatar || DeAvatar) + '?x-oss-process=image/resize,m_fill,w_60,quality,q_60'"/>
                  </div>
                </el-badge>

                <!-- 名称 -->
                <div class="list-con">
                  <p class="concat-title">
                    <span>{{ successItem.name }}</span>
                    <!-- <span class="title-time"> {{ concatItem.createTime }}</span> -->
                    <span class="title-time">
                      {{ getTime2(successItem) }}</span>
                  </p>
                  <p class="message">
                    <!-- <i class="el-icon-circle-check"></i> -->
                    <span >{{matchMsg(successItem)}}</span>
                  </p>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <!-- 订单服务 end -->
      </div>
    </NewCard>

    <el-drawer :title="'发起聊天'" :visible.sync="drawer2" size="30%" direction="rtl">
      <addImOne @change="drawer2 = false"></addImOne>
    </el-drawer>

    <el-drawer :title="'发起群聊'" :visible.sync="drawer" size="30%" direction="rtl">
      <addImGroup @change="drawer = false"></addImGroup>
    </el-drawer>
  </div>
</template>

<script>
  import {
    mapGetters,
    mapState,
  } from "vuex";
  import {
    getMessageList,
    getName,
    getAllOrderNoList,
    getImList,
  } from "@/BMViews/api/upload/index.js";
  import NewCard from "@/wss/components/newCard.vue";
  import {
    formatDate
  } from "@/utils/index.js";
  import addImOne from "./im/addImOne.vue"
  import addImGroup from "./im/addImGroup.vue"

  //防抖：debounce 用户触发事件过于频繁，只要最后一次事件的操作
  import debounce from "lodash/debounce";

  export default {
    components: {
      NewCard,
      addImOne,
      addImGroup
    },
    props: {
      aviTab: {
        type: Number,
        default: 1,
      }
    },
    data() {
      return {
        showSearch: 1, //当前激活的tab
        messageNum: "",
        activeNames: "1",
        update: false,
        isShowNewOrder: false,
        newOrderNo: {}, //新的订单提醒
        // 接收点击过来的参数的那一项
        // 用于过滤
        filConList: [],
        filterSuccessList: [],
        filterHavingList: [],
        // 输入的关键词
        keyword: "",
        //   当前选中的li 默认选中第一个
        currentIndex: 0,
        // 订单列表
        concatList: [],
        // 进行中的订单
        havingList: [],
        // 已完成的列表
        successList: [],
        // 头像颜色设置
        // colorlists: ["#2C9BFB", "#00C3AA", "#FD9A24", "#4E57D6"],
        // 成员
        friendArr: [],

        // 最后一条消息
        msg: "",
        // // 当前群的人员
        // currentMembers: [],
        // 总的消息数
        MagNumber: 0,
        // 消息记录
        chatMessages: [],
        // 已读的人
        readMber: [],
        // 本订单的未读数量
        unread: "",
        //订单展示
        pageNum: 1,
        pageSize: 10,
        // 订单总数
        total: 0,
        totalList: [],

        // 进行中的全部订单条数
        havingListAll: [],
        //已完成的全部订单条数
        successListAll: [],

        //私聊订单
        imList: [],
        imUserList: [],
        DeAvatar: require("@/assets/images/defaultAvatar.jpg"),
        //添加菜单显示隐藏
        menuShow: false,
        drawer: false, //弹窗显示
        drawer2: false, //弹窗显示

        //任务目标未读数量
        taskUnreadNum:0,
        //订单服务未读数量
        orderUnreadNum:0,
        //任务列表
        taskList:[],
        // 头像颜色设置
        colorlists: [
          require("@/assets/images/img4.jpg"),
          require("@/assets/images/img1.jpg"),
          require("@/assets/images/img2.jpg"),
          require("@/assets/images/img3.jpg")
        ],
        //私聊全部列表
        imListAll:[],
        //任务全部列表
        taskListAll:[],
        //订单全部列表
        filConListAll:[],
      };
    },
    async created() {
      await this.getImList();
      await this.getTaskList();
      await this.getCircleUserList();

      //路由接参数
      let sessionId = this.$route.query.id;
      if (sessionId) {
        let imInfo = this.imList.find((item) => {
          return item.id == sessionId;
        });
        if (imInfo) {
          this.chatIm(imInfo)
        }
      }
      // 路由传参接收
      // let orderId = this.$route.query.orderId;
      // if (orderId) {
      //   let filterId = this.concatList.find((item) => {
      //     return item.id == orderId;
      //   });
      //   if (filterId) {
      //     this.currentIndex = filterId.id;
      //     this.chatSay(
      //       filterId.name,
      //       "",
      //       filterId.color,
      //       filterId.id,
      //       filterId.cancelTime,
      //       filterId.members.length,
      //       filterId.type,
      //       filterId.title,
      //       filterId.members
      //     );
      //   }
      // }
    },
    mounted() {
      //赋值默认tab
      this.showSearch = this.aviTab
      // 更新页面渲染
      // this.$bus.$on("uploadMessage", (data) => {
      //   // 隐藏项目
      //   this.messageHandler(data);
      // });
      //创建聊天室刷新列表
      this.$bus.$on('updataImList', async (res) => {
        console.log(res,'duandian...............');
        await this.getImList();
        if(res.id){
          let resss = this.imList.find(item=>item.id == res.id)
          this.chatIm(resss);
        }
      })

      this.$bus.$on('uploadImListNum', (res) => {
        console.log('接收wss消息数量', res);
        this.imList.filter(item => {
          if (item.id == res.no) {
            console.log('接收wss消息数量222222', item);
            if(item.imMessage && res.data.msgid == item.imMessage.id && res.type == 3){
              //消息撤回
              item.imMessage.status = -1
            }else{
              if(res.type == 3) return false;
              res.data.createTime = formatDate(res.data.createTime)
              item.imMessage = res.data;
              if(res.data.createBy != this.userId){
                item.unreadNumber = parseFloat(item.unreadNumber) + 1
              }
            }
          }
        })
      })

      this.$bus.$on('uploadOmListNum', (res) => {
        console.log('接收wss消息数量', res);
        this.filConList.filter(item => {
          if (item.id == res.no) {
            console.log('接收wss消息数量222222', item);
            res.data.createTime = formatDate(res.data.createTime)
            item.lastMessage = res.data;
            item.unread = parseFloat(item.unread) + 1
          }
        })
        // this.filterSuccessList.filter(item => {
        //   if (item.id == res.no) {
        //     console.log('接收wss消息数量222222', item);
        //     res.data.createTime = formatDate(res.data.createTime)
        //     item.lastMessage = res.data;
        //     item.unread = parseFloat(item.unread) + 1
        //   }
        // })
      })

      // console.log(this.totalList);
      // this.$refs.box.$el.addEventListener("scroll", this.lazyLoading); // 滚动到底部，再加载的处理事件
      //接收最后一条消息
      this.$bus.$on("message", (content, orderNo, num, createBy) => {
        this.concatList.forEach((item) => {
          if (item.id == orderNo) {
            this.$set(item, "msg", content);
            if (this.currentIndex == item.id) {
              // console.log(this.currentIndex, "99999999999999");
              this.$set(item, "unread", 0);
              this.$bus.$emit("numSum", 0);
              // console.log("333333333333");
            } else {
              this.$set(item, "unread", num);
            }
          }
        });
      });
    },

    methods: {
      //打开添加单聊弹窗
      openAddOne() {
        this.menuShow = false;
        this.drawer2 = true
      },
      //打开添加群聊弹窗
      openAddGroup() {
        this.menuShow = false;
        this.drawer = true
      },
      // 截取时间

      // 两个Date对象相减获得的小时
      // getTime(start, end) {
      //   return (hours = parseInt((endDate - beginDate) / (1000 * 60 * 60)));

      // 下面判断是需不需要加上分钟，如果需要加上分钟就是时间加一，否则直接返回小时，无需下面操作
      // //计算天数后剩余的毫秒数
      // let leave1 =
      //   (endDate.getTime() - beginDate.getTime()) % (24 * 3600 * 1000);
      // let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
      // let minutes = Math.floor(leave2 / (60 * 1000));
      // return minutes == "0" ? hours : hours + 1;
      // },

      // 点击每个跳转到不同的聊天对话框
      chatSay(
        name,
        index,
        color,
        id,
        cancelTime,
        memberLength,
        type,
        title,
        member
      ) {
        // console.log(title, "1111111111111111111111111111111111");
        this.currentIndex = id;
        // this.totalList.forEach((item) => {
        //   if (item.id == id) {
        //     console.log(item.unread, "数量1111111");
        //     if (item.unread && item.unread != 0) {
        //       this.$WebSocket.reduceNum(item.unread);
        //     }
        //     this.$set(item, "unread", 0);
        //     // this.$bus.$emit("ClikSum", 0);
        //   }
        // });
        this.concatList.forEach((item) => {
          if (item.id == id) {
            // console.log(item.unread, "数量1111111");
            // if (item.unread && item.unread != 0) {
            this.$WebSocket.reduceNum(item.unread);
            // }
            this.$set(item, "unread", 0);
          }
        });
        //  获取成员
        // console.log(member, "membermembermembermembermembermembermember");
        let nameArr = [];
        member?.forEach((item) => {
          // console.log(item.userid);
          nameArr.push(item.userid);
          this.getName(nameArr, member);
        });
        let num = 0;
        this.$bus.$emit("sumS", num, id);

        let members = member.filter((item) => {
          return item.status != -1;
        });
        // console.log(reads);

        //向设置页传输内容
        this.$bus.$emit(
          "currentChat",
          name,
          color,
          id,
          cancelTime,
          members.length,
          type,
          title
        );
      },
      async chatSay2(data, index) {
        console.log(data);
        this.currentIndex = data.id;
        this.$emit('onClickList', data)

        //总数量减去未读消息数量
        //减少数量
        this.$store.dispatch('chat/subUnread',{
          'orderUnread': data.unread
        })
        // this.$WebSocket.reduceNum(data.unread);
        this.$set(data, "unread", 0);

        //  获取成员
        let userIds = data.members?.map(item => (item.userid));
        let userList = await getName({
          userIds: userIds?.join(',')
        })
        if (userList.code == 200) {
          data.userList = userList.data
          //向聊天记录页发送用户列表
          this.$bus.$emit("friendArr", data.userList, data.members);
        }

        // let nameArr = [];
        // data.members?.forEach((item) => {
        //   // console.log(item.userid);
        //   nameArr.push(item.userid);
        // });
        // let num = 0;
        // this.$bus.$emit("sumS", num, data.id);

        let members = data.members.filter((item) => {
          return item.status != -1;
        });
        // console.log(data.members, "membermembermembermembermembermembermember");

        // console.log(reads);

        // 向设置页传输内容
        this.$bus.$emit(
          "currentChat",
          data.name,
          data.color,
          data.id,
          data.cancelTime,
          data.members,
          data.type,
          data.title
        );
      },
      //点击私聊
      chatIm: debounce(function(data){
        console.log(data,'duandian.................');
        if (!data) return;
        this.currentIndex = data.id;
        //查询用户信息
        // console.log(data);
        let userInfo = this.imUserList.find(item => item.userId == data.userPid)
        data.userInfo = userInfo;
        // this.$WebSocket2.reduceNum(data.unreadNumber);
        //减少数量
        switch (data.type){
          case '0':
          case '1':
            this.$store.dispatch('chat/subUnread',{
              'imUnread': data.unreadNumber
            })
            break;
          case '01':
          case '02':
            this.$store.dispatch('chat/subUnread',{
              'taskUnread': data.unreadNumber
            })
            break;
          default:
            break;
        }
        this.$set(data, "unreadNumber", 0);
        this.$emit('onClickList', data)
      },500),

      //获取新消息提醒
      messageHandler(data) {
        if (data.type == "5") {
          //来新的订单
          // console.log(data, "新的订单新的订单");
          this.isShowNewOrder = true;
          //如果是专家才会有提醒
          // if(){

          // }
        } else {
          return;
        }
      },

      //获取私聊列表
      async getImList() {
        try {
          const {
            code,
            rows
          } = await getImList({type:'0；1'});
          // this.imList = rows;
          console.log(rows,'成员..................');
          let resList = rows;
          let userList = [];
          for (let i = 0; i < resList.length; i++) {
            //获取成员信息
            let userIds = resList[i].members?.map(item => {
              if (item.userid != this.$store.state.user.userId) {
                //如果非自己id为对方id
                resList[i].userPid = item.userid
              }
              return item.userid;
            });
            if (!userIds) {
              // return false
              continue;

            }
            userList = [...userList, ...userIds];
          }
          //去重
          userList = [...new Set(userList)]
          //获取用户数据
          let resUserList = await this.getUserInfo(userList);
          console.log(resUserList);
          resList.forEach(item => {

            let userInfo = resUserList.find(items => item.userPid == items.userId)
            // console.log(userInfo, '111111111111');
            if (userInfo) {
              item.icon = userInfo?.avatar
              if(!item.name){
                item.name = userInfo?.nickName
              }
            }
            let avatarArr = [];
            item.members?.filter(item => {
            	if(item.status != -1){
            		let userInfo = resUserList.find(items=> (items.userId == item.userid))
            		if(userInfo){
            			avatarArr.push(userInfo);
            		}
            	}
            })
            item.avatarArr = avatarArr;

          })
          console.log(resList);
          this.imList = resList;
          this.imListAll = resList;
          let unread = resList.reduce((a,b) => a + Number(b.unreadNumber),0);
          console.log('vuexs',this.$store);
          // this.$store.dispatch('chat/setUnread',{
          //   'imUnread': unread
          // })
        } catch (err) {
          console.log(err);
        }
      },
      //获取任务列表
      async getTaskList() {
        try {
          const {
            code,
            rows
          } = await getImList({type:'01；02',status:1});
          // this.imList = rows;
          console.log(rows,'成员..................');

          let resList = rows;
          let userList = [];
          for (let i = 0; i < resList.length; i++) {
            //获取成员信息
            let userIds = resList[i].members?.map(item => {
              if (item.userid != this.$store.state.user.userId) {
                //如果非自己id为对方id
                resList[i].userPid = item.userid
              }
              return item.userid;
            });
            if (!userIds) {
              // return false
              continue;

            }
            userList = [...userList, ...userIds];
          }
          //去重
          userList = [...new Set(userList)]
          //获取用户数据
          let resUserList = await this.getUserInfo(userList);
          console.log(resUserList);
          resList.forEach(item => {

            let userInfo = resUserList.find(items => item.userPid == items.userId)
            // console.log(userInfo, '111111111111');
            if (userInfo) {
              item.icon = userInfo?.avatar
              if(!item.name){
                item.name = userInfo?.nickName
              }
            }
            let avatarArr = [];
            item.members?.filter(item => {
            	if(item.status != -1){
            		let userInfo = resUserList.find(items=> (items.userId == item.userid))
            		if(userInfo){
            			avatarArr.push(userInfo);
            		}
            	}
            })
            item.avatarArr = avatarArr;

          })
          console.log(resList);
          this.taskList = resList;
          this.taskListAll = resList;
          let unread = resList.reduce((a,b) => a + Number(b.unreadNumber),0);
          this.$store.dispatch('chat/setUnread',{
            'taskUnread': unread
          })
          this.taskUnreadNum = unread;
        } catch (err) {
          console.log(err);
        }
      },
      //获取用户
      async getUserInfo(name) {
        const {
          data
        } = await getName({
          userIds: name?.join(',')
        });
        this.imUserList =[...this.imUserList,...data];
        console.log("cyccyyyyyyyyyyyyyyyyyyyyy",this.imUserList);
        //用户列表存入vuex
        this.$store.state.chat.chatUserList = this.imUserList;
        return data;
      },
      //获取头像
      getImAvatar(data) {
        let info = this.imUserList.find(item => data.userPid == item.userId)
        console.log(info, '6666666666666')
        return info?.avatar
      },
      //获取名称
      getImName(data) {
        let info = this.imUserList.find(item => data.userPid == item.userId)
        return info?.nickName
      },
      //获取头像
      getGroupAvatar(data) {
      	console.log('获取头像',data);
        if(!data?.avatarArr) return;
        let aaa = JSON.parse(JSON.stringify(data?.avatarArr?.slice(0,9)))
        //不足数量补色块
        if(aaa.length < 9 && aaa.length > 4){
        	var index = 0;
        	var num = 9 - aaa.length;
        	for(let i = 0; i < num; i++){
        		if(index > 3){
        			index = 0;
        		}
        		aaa.push({
        			isFill: 1,
        			avatar: this.colorlists[index]
        		})
        		index++
        	}
        }else if(aaa.length < 4){
        	var index = 0;
        	var num = 4 - aaa.length;
        	for(let i = 0; i< num; i++){
        		if(index > 3){
        			index = 0;
        		}
        		aaa.push({
        			isFill: 1,
        			avatar: this.colorlists[index]
        		})
        		index++
        	}
        }
        console.log('处理后头像',aaa);
        return aaa
      	// data = data.slice(0,9)
      	// let arr = [];
      	// for (let i = 0; i < data.length; i++) {
      	// 	let info = this.imUserList.find(item => data[i].userid == item.userId);
       //    arr.push(info?.avatar);
      	// }
       //  // console.log(arr);
      	// data.avatarList = arr
      	// return arr
      },
      getMembersNum(data){
      	return data?.length ? data?.length : 0
      },
      getIcon(id) {
        let list = this.$store.state.chat.consultTypeList;
        let list2 = this.$store.state.chat.projectTypeList;
        let res = list.find(item => item.id == id);
        let res2 = list2.find(item => item.id == id);
        if (res2) {
          return res2?.icon1;
        } else {
          return res?.icon1;
        }
      },
      // 获取加载的订单数据
      async getCircleUserList() {
        try {
          const {
            code,
            data
          } = await getMessageList({
            // pageNum: this.pageNum,
            // pageSize: this.pageSize,
          });
          // console.log(data, "让我看看");
          // 要加上之前的订单
          let resList = data.rows;

          //补全数据
          let userList = [];
          for (let i = 0; i < resList.length; i++) {
          	//获取成员信息
          	let userIds = resList[i].members?.map(item => {
          		return item.userid;
          	});
          	if (!userIds) {
          		// return false
          		continue;
          	}
          	userList = [...userList, ...userIds];
          }
          userList = [...new Set(userList)]
          //获取用户数据
          let userListRes = await this.getUserInfo(userList);
          console.log('获取订单用户', userListRes);
          resList.filter(item=>{
          	//群聊天
          	let avatarArr = []
          	item.members?.filter(item => {
          		if(item.status != -1){
          			let userInfo = userListRes.find(items=> (items.userId == item.userid))
          			if(userInfo){
          				avatarArr.push(userInfo);
          			}
          		}
          	})
          	item.avatarArr = avatarArr;
          })

          // this.concatList.push(...resList);
          this.concatList = resList;
          // this.$bus.$emit("concatList", this.concatList);
          this.total = data.total;

          // console.log(this.concatList, "订单列表订单列表订单列表订单列表");
          this.filConList = JSON.parse(JSON.stringify(this.concatList));
          let unread = this.filConList.reduce((a,b) => a + Number(b.unread),0);
          console.log('订单未读2',unread);
          this.$store.dispatch('chat/setUnread',{
            'orderUnread': unread
          })
          this.orderUnreadNum = unread


          // // 过滤已完成的订单
          // this.successList = this.concatList.filter((item) => {
          //   // 如果超过当前时间则不能再聊天算已完成
          //   let SuccessTime = item.cancelTime;
          //   let newDate = this.getDate(new Date());
          //   if (newDate > SuccessTime) {
          //     // let days = this.DateMinus(SuccessTime, newDate);
          //     // if (days >= 3) {
          //     return item;
          //     // }
          //   } else {
          //     return;
          //   }
          // });
          // // console.log(this.successList, "已完成已完成已完成已完成");
          // // 初始化过滤使用
          // this.filterSuccessList = this.successList;

          // // 进行中的订单
          // this.havingList = this.concatList.filter((item) => {
          //   return this.successList.every((itemB) => {
          //     // console.log(itemB, "88888888888888888888888888");
          //     return item.id != itemB.id;
          //   });
          // });
          // // console.log(this.havingList, "进行中进行中进行中进行中进行中");
          // this.filterHavingList = this.havingList;
          // if (this.filterHavingList.length == 0) {
          //   // 让第二个折叠层默认展示
          //   this.activeNames = "3";
          //   this.currentIndex = this.successList[0].id;
          // }
        } catch (err) {
          console.log(err);
        }
      },
      // 获取姓名
      async getName(name, member) {
        const {
          data
        } = await getName({
          userIds: name.join(",")
        });
        // console.log(data, "cyccyyyyyyyyyyyyyyyyyyyyy");
        this.friendArr = data;
        // console.log(this.friendArr, "成员成员成员成员成员成员");
        this.$bus.$emit("friendArr", this.friendArr, member);
      },
      // 滚动加载
      lazyLoading(e) {
        const scrollTop = e.target.scrollTop; // 滚动条滚动时，距离顶部的距离
        const windowHeight = e.target.clientHeight; // 可视区的高度
        const scrollHeight = e.target.scrollHeight; // 滚动条的总高度
        // 滚动条到底部
        if (scrollTop + windowHeight === scrollHeight) {
          this.pageNum++;
          let pageCount = (this.total + this.pageSize - 1) / this.pageSize;
          console.log(pageCount);
          // console.log(this.total);
          console.log(this.pageNum);
          if (this.pageNum >= pageCount) return;
          this.getCircleUserList();
        }
      },



      //获取第一二个汉字
      getHanzi(name) {
        if (name) {
          let arr = name.split("");
          let reg =
            /^(\d+$|[a-z]+$|[A-Z]+$|[` ~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]+$|((?=[!-~])[^\da-zA-Z])+$)/;
          let str = "";
          for (let i = 0; i < arr.length; i++) {
            if (!reg.test(arr[i])) {
              return arr[i] + arr[i + 1];
            }
          }
        }
      },

      getMsg(message) {
        if (message?.length >= 1) {
          if (this.matchType(message[message.length - 1].msg) == "image") {
            return "【图片】";
          } else if (
            this.matchType(message[message.length - 1].msg) == "pdf" ||
            this.matchType(message[message.length - 1].msg) == "ppt" ||
            this.matchType(message[message.length - 1].msg) == "word" ||
            this.matchType(message[message.length - 1].msg) == "excel" ||
            this.matchType(message[message.length - 1].msg) == "txt"
          ) {
            return "【文件】";
          } else if (this.matchType(message[message.length - 1].msg) == "video") {
            return "【视频】";
          } else if (this.matchType(message[message.length - 1].msg) == "radio") {
            return "【音频】";
          } else if (this.matchType(message[message.length - 1].msg) == "zip") {
            return "【压缩包】";
          } else {
            return message[message.length - 1].msg;
          }
        }
      },
      matchMsg(msg) {
        // console.log(msg, "88888888888888888888888888888888888");
        if(msg?.lastMessage && msg?.lastMessage?.status == -1){
          return '消息已撤回';
        }
        msg = msg?.lastMessage?.msg

        if (msg) {
          if (
            this.matchType(msg) == "pdf" ||
            this.matchType(msg) == "ppt" ||
            this.matchType(msg) == "word" ||
            this.matchType(msg) == "excel" ||
            this.matchType(msg) == "txt"
          ) {
            return "【文件】";
          } else if (this.matchType(msg) == "zip") {
            return "【压缩包】";
          } else if (this.matchType(msg) == "image") {
            return "【图片】";
          } else if (this.matchType(msg) == "radio") {
            return "【音频】";
          } else if (this.matchType(msg) == "video") {
            return "【视频】";
          } else {
            return msg;
          }
        }
      },
      // 时间格式
      getTime(message) {
        if (message?.length >= 1) {
          let time = message[message.length - 1]?.createTime;
          let JqTime = time?.substring(0, 10);
          let newDate = this.getDate(new Date());
          let days = this.DateMinus(JqTime, newDate);
          if (days >= 1) {
            return time?.substring(5, 10).replace(/\-/, "月") + "日";
          }
          return time?.substring(time?.length - 8, time?.length - 3);
        }
      },
      // 私聊时间格式
      getTime2(item) {
        let message = item?.imMessage || item?.lastMessage;
        // console.log('获取时间',message);
        if (message) {
          let time = message?.createTime;
          let JqTime = time?.substring(0, 10);
          let newDate = this.getDate(new Date());
          let days = this.DateMinus(JqTime, newDate);
          if (days >= 1) {
            return time?.substring(5, 10).replace(/\-/, "月") + "日";
          }
          return time?.substring(time?.length - 8, time?.length - 3);
        }
      },
      getImMsg(item) {
        let message = item.imMessage;
        if(message?.status == -1){
          return '消息已撤回';
        }
        if (message) {
          if (this.matchType(message.msg) == "image") {
            return "【图片】";
          } else if (
            this.matchType(message.msg) == "pdf" ||
            this.matchType(message.msg) == "ppt" ||
            this.matchType(message.msg) == "word" ||
            this.matchType(message.msg) == "excel" ||
            this.matchType(message.msg) == "txt"
          ) {
            return "【文件】";
          } else if (this.matchType(message.msg) == "video") {
            return "【视频】";
          } else if (this.matchType(message.msg) == "radio") {
            return "【音频】";
          } else if (this.matchType(message.msg) == "zip") {
            return "【压缩包】";
          } else {
            let abc = message.msg.replace(/<br>|<br\/>/g, " ")
            return abc;
          }
        }
      },
      // 时间天数
      DateMinus(date1, date2) {
        //date1:小日期   date2:大日期
        var sdate = new Date(date1);
        var now = new Date(date2);
        var days = now.getTime() - sdate.getTime();
        var day = parseInt(days / (1000 * 60 * 60 * 24));
        return day;
      },

      //转换时间方法
      getDate(date) {
        //date是传过来的时间戳，注意需为13位，10位需*1000
        //也可以不传,获取的就是当前时间
        var time = new Date(date);
        var year = time.getFullYear(); //年
        var month = ("0" + (time.getMonth() + 1)).slice(-2); //月
        var day = ("0" + time.getDate()).slice(-2); //日
        var hour = ("0" + time.getHours()).slice(-2); //小时
        var mun = ("0" + time.getMinutes()).slice(-2); //分钟
        var seconds = ("0" + time.getSeconds()).slice(-2); //秒
        var mydate =
          year + "-" + month + "-" + day + " " + hour + ":" + mun + ":" + seconds;
        return mydate;
      },

      // 判断图片文件
      matchType(fileName) {
        // 后缀获取
        var suffix = "";
        // 获取类型结果
        var result = "";
        try {
          var flieArr = fileName.split(".");
          suffix = flieArr[flieArr.length - 1];
        } catch (err) {
          suffix = "";
        }
        // fileName无后缀返回 false
        if (!suffix) {
          result = false;
          return result;
        }
        // 图片格式
        var imglist = ["png", "jpg", "jpeg", "bmp", "gif", "JPG", "PNG", "GIF"];
        // 进行图片匹配
        result = imglist.some(function(item) {
          return item == suffix;
        });
        if (result) {
          result = "image";
          return result;
        }
        // 匹配txt
        var txtlist = ["txt"];
        result = txtlist.some(function(item) {
          return item == suffix;
        });
        if (result) {
          result = "txt";
          return result;
        }
        // 匹配 excel
        var excelist = ["xls", "xlsx", "numbers"];
        result = excelist.some(function(item) {
          return item == suffix;
        });
        if (result) {
          result = "excel";
          return result;
        }
        // 匹配 word
        var wordlist = ["doc", "docx"];
        result = wordlist.some(function(item) {
          return item == suffix;
        });
        if (result) {
          result = "word";
          return result;
        }
        // 匹配 pdf
        var pdflist = ["pdf", "PDF"];
        result = pdflist.some(function(item) {
          return item == suffix;
        });
        if (result) {
          result = "pdf";
          return result;
        }
        // 匹配zip
        var ziplist = ["zip", "rar", "exe", "tgz"];
        result = ziplist.some(function(item) {
          return item == suffix;
        });
        if (result) {
          result = "zip";
          return result;
        }
        // 匹配 ppt
        var pptlist = ["ppt", "pptx", "key"];
        result = pptlist.some(function(item) {
          return item == suffix;
        });
        if (result) {
          result = "ppt";
          return result;
        }
        // 匹配 视频
        var videolist = ["mp4", "m2v", "mkv"];
        result = videolist.some(function(item) {
          return item == suffix;
        });
        if (result) {
          result = "video";
          return result;
        }
        // 匹配 音频
        var radiolist = ["mp3", "wav", "wmv"];
        result = radiolist.some(function(item) {
          return item == suffix;
        });
        if (result) {
          result = "radio";
          return result;
        }
        // 其他 文件类型
        result = "other";
        return result;
      },
      // 已读
      readMessage() {},
    },
    // 截取字符串
    // concatList.forEach((item) => {
    //   if (item.remark) {
    //     item.remark = item.remark.slice(
    //       item.remark.indexOf("：") + 1,
    //       item.remark.lastIndexOf("；")
    //     );
    //   }
    //   item.color =
    //     this.colorlists[Math.floor(Math.random() * this.colorlists.length)];
    // });
    computed: {
      ...mapGetters(["token", "avatar", "userId", "userType", "name","chatUserList"]),
      // // 计算总消息数
    },
    watch: {
      // // 监听输入的搜索关键词（第一种方法）
      keyword: {
        immediate: true,
        handler(val) {
          // this.activeNames = ["1", "2"];
          if (this.showSearch == 1) {
            if(!val){
              this.imList = this.imListAll
              return false;
            }
            this.imList = this.imListAll.filter((item) => {
              if (!item.name) return false;
              return item.name.indexOf(val) !== -1;
            });
          } else if (this.showSearch == 2) {
            if(!val){
              this.taskList = this.taskListAll
              return false;
            }
            this.taskList = this.taskListAll.filter((item) => {
              if (!item.name) return false;
              return item.name.indexOf(val) !== -1;
            });
          } else if (this.showSearch == 3) {
            if(!val){
              this.filConList = JSON.parse(JSON.stringify(this.concatList))
              return false;
            }
            this.filConList = this.concatList.filter((item) => {
              if (!item.name) return false;
              return item.name.indexOf(val) !== -1;
            });
          }
        },

      },
      //监听vuex中任务未读数变化
      '$store.state.chat.taskUnread': {
      	deep: !0,
        immediate: true,
      	handler: function(newValue, oldValue) {
          console.log('监听到消息数变化',newValue);
          this.taskUnreadNum = newValue;
        }
      },
      //监听vuex中任务未读数变化
      '$store.state.chat.orderUnread': {
      	deep: !0,
        immediate: true,
      	handler: function(newValue, oldValue) {
          console.log('监听到消息数变化',newValue);
          this.orderUnreadNum = newValue;
        }
      },
      totalList: {
        handler(totalList) {
          let sum1 = 0;
          //  去遍历每一项，如果每一项都有消息，则把它们消息的数量相加
          // console.log(totalList, "所有订单所有订单");
          totalList.forEach((item) => {
            return (sum1 += item.unread || 0);
          });
          // this.messageNum = sum;
          // this.$bus.$emit("messageNum", sum1);
        },
        deep: true,
        immediate: true,
      },
      //监听选项卡切换
      showSearch: {
        immediate: true,
        handler(val) {
          // this.$refs.box.$el.addEventListener("scroll", this.lazyLoading); // 滚动到底部，再加载的处理事件
          this.keyword = '';
          if (val == 1) {
            this.chatIm(this.imList[0])
          } else if (val == 2) {
            this.chatIm(this.taskList[0])
          } else if (val == 3) {
            this.chatSay2(this.filConList[0])
          }
          this.$emit('update:aviTab', this.showSearch)
        },
      }
    },
    directives: {
      trigger: {
        inserted(el, {
          value
        }) {
          el.id == "0" ? el.click() : null; // 只点击第一个，id是在循环中手动添加的
        },
      },
    },
    destroyed() {
      // this.$bus.$off("uploadMessage");
    },
  };
</script>

<style scoped>
  * {
    margin: 0;
    padding: 0;
  }

  ::v-deep .el-collapse {
    border: none;
  }

  .display {
    display: none;
  }

  ::v-deep .el-collapse-item .el-collapse-item__header {
    border: none;
    padding: 0 16px;
    font-weight: 700;
    font-size: 14px;
    color: #8f959e;
  }

  ul li {
    list-style: none;
  }

  ::v-depp .el-card__body .top .left {
    padding: 30px;
  }

  .chatList>>>.el-card__body {
    padding: 0;
    height: 100%;
  }

  .chatList>>>.el-card__body>div {
    height: calc(100% - 76px);
    overflow-y: auto;
    scrollbar-width: thin;
    /* 火狐滚动条无法自定义宽度，只能通过此属性使滚动条宽度变细 */
  }

  .chatList>>>.el-card__body>div::-webkit-scrollbar {
    width: 0 !important;
  }

  /* 切换的按钮标题 */
  .chatList>>>.el-radio-group {
    border-radius: 10px;
    width: 100%;
  }

  .chatList>>>.el-radio-group .el-radio-button {
    width: 33%;
  }

  .chatList>>>.el-radio-button__orig-radio+.el-radio-button__inner {
    background-color: #f0f2f5;
    width: 100%;
    padding: 10px 0;
  }

  .chatList>>>.el-radio-button__orig-radio+.el-radio-button__inner:hover {
    color: #f87a23;
  }

  .chatList>>>.el-radio-button__orig-radio:checked+.el-radio-button__inner {
    background-color: #fff;
    border-color: #f0f2f5;
    color: #f87a23;
    font-weight: 700;
    box-shadow: none;
  }

  /* 人员列表 */
  .chatList>>>.top .left h1 b {
    width: calc(100% - 20px);
  }

  .chatList {
    height: 100%;
    overflow: hidden;
  }

  .chatList>>>.el-card__body .top {
    margin: 0 16px;
    /* padding: 15px 0 6px 0; */
  }

  .list-box {
    width: 100%;
    height: calc(100%-46px);
    overflow-y: auto;
    scrollbar-width: none;
  }

  ::v-deep .el-collapse-item__content {
    position: relative;
  }

  ::v-deep .el-collapse-item__content .Group_error {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    line-height: 40px;
    cursor: pointer;
    z-index: 9;
  }

  .list-box li {
    padding: 15px 16px;
    display: flex;
    /* align-items: center;
justify-content: space-between; */
    flex-shrink: 0;
    /* flex-wrap: wrap; 会挤压换行 */
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    /* border-bottom: 2px solid #000; */
  }

  .list-box li .avatarImg {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    box-sizing: border-box;
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 8px;
  }

  .list-box li .avatarImg img {
    width: 60%;
    height: 60%;
  }

  .list-box li.active {
    /* background-color: #e7f0ff; */
    background-color: #f5f5f5;
  }

  .list-box li .avatar {
    /* margin-right: 10px; */
    font-size: 12px;
    display: block;
    border-radius: 8px;
  }

  ::v-deep .el-badge__content.is-fixed {
    position: absolute;
    top: 4px;
    right: 15px;
  }

  ::v-deep .el-badge__content {
    border: none;
    width: 20px;
    height: 20px;
    padding: 0;
    line-height: 20px;
  }

  .list-box li .list-con {
    display: flex;
    flex: 1;
    width: 80%;
    flex-direction: column;
    display: inline-block;
    font-size: 14px;
    margin-left: 12px;
    /* margin-top: -4px; */
  }

  .search-list {
    padding: 0 16px;
    margin-bottom: 10px;
  }

  .list-box li div .concat-title {
    font-weight: 600;
    color: #2e3f5e;
    display: flex;
    justify-content: space-between;
  }

  .list-box li div .concat-title span:nth-child(1) {
    display: inline-block;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }

  .list-box li div .concat-title .title-time {
    color: #8f959e;
    font-size: 12px;
    font-weight: 400;
  }

  .list-box li div .message {
    display: flex;
    color: #8f959e;
    font-size: 12px;
    margin-top: 2px;
    position: relative;
  }

  .list-box li div .message .message_pic {
    position: absolute;
    right: 0;
    top: 0;
  }

  .list-box li div .message i {
    color: #06b49c;
    font-size: 14px;
    padding-top: 2px;
    padding-right: 5px;
    vertical-align: middle;
  }

  .list-box li div .message span {
    font-size: 12px;
    color: #8f959e;
    display: block;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }

  /* 滚动条 */
  ::-webkit-scrollbar {
    /* display: none; */
    /*滚动条整体样式*/
    width: 0px;
    /*高宽分别对应横竖滚动条的尺寸*/
    /* height: 5px; */
  }

  /* 私聊 */

  .list-box li .avatarImg2 {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    box-sizing: content-box;
    background-color: #dcdcdc;
    border: 1px solid #dcdcdc;
    border-radius: 5px;
    overflow: hidden;
  }

  .list-box li .avatarImg2 img {
    width: 100%;
    height: 100%;
  }

  /*发起群聊*/
  .addIcon {
    display: flex;
    padding-left: 5px;
    position: relative;
  }

  .addIcon img {
    width: 24px;
    height: 24px;
  }

  .menubox {
    position: absolute;
    z-index: 9999999999999999;
    right: 0px;
    top: 30px;
  }

  .menubox .list {
    position: relative;
    padding: 0 15px;
    background: #F0F4FF;
    border-radius: 8px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  }

  .menubox .list:before {
    content: '';
    width: 0;
    height: 0;
    position: absolute;
    top: -10px;
    right: 8px;
    border: 5px solid transparent;
    border-bottom: 5px solid #F0F4FF;
  }

  .menubox .item {
    padding: 10px 6px;
    border-bottom: 2px solid rgba(15, 23, 99, 0.06);
  }

  .menubox .item span {
    color: #0F1763;
    font-size: 13px;
    white-space: nowrap;
  }

  .menubox .item:last-child {
    border: 0;
  }

  .menubox .mask_bg {
    position: fixed;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
  }

  /*群聊头像*/
  .groupAvatar{
  	display: flex;
  	align-items: center;
  	justify-content: center;
  	flex-wrap: wrap;
  }
  .groupAvatar img{
  	width: 12px !important;
  	height: 12px !important;
  }
  .groupAvatar.big img {
    width: 20px !important;
    height: 20px !important;
  }
  .back{
    font-size: 12px;
    padding:0 15px;
    color:#999;
    padding-bottom: 15px;
  }
</style>
